# -*- coding: utf-8 -*-
'''
Created on Sep 8, 2012

@author: bbg
'''
import binascii
import locale
import time,datetime
from service.public.service_base import ServiceBase
from helper.login_session_manager import LoginSessionManager
from helper.cdkey_manager import CdkeyManager 
from common.debug import Debug
from dbwrapper.shopx.config_cook_method_class import ConfigCookMethodClass
from dbwrapper.shopx.config_cook_method  import ConfigCookMethod
from dbwrapper.shopx.config_cook_relation import ConfigCookRelation
from dbwrapper.shopx.config_dish_class import ConfigDishClass
from dbwrapper.shopx.config_dish import ConfigDish
from dbwrapper.shopx.config_floor import ConfigFloor
from dbwrapper.shopx.config_order_mode import ConfigOrderMode
from dbwrapper.shopx.config_payment import ConfigPayment
from dbwrapper.shopx.config_printers import ConfigPrinters
from dbwrapper.shopx.config_reason import ConfigReason
from dbwrapper.shopx.config_room import ConfigRoom
from dbwrapper.shopx.config_stat_class import ConfigStatClass
from dbwrapper.shopx.config_unit_relation import ConfigUnitRelation
from dbwrapper.shopx.order_dishes import OrderDishes
from dbwrapper.shopx.order_main import OrderMain
from dbwrapper.shopx.order_payment_mode import OrderPaymentMode
from dbwrapper.shopx.order_subdishes import OrderSubdishes
from dbwrapper.shopx import *
import dbwrapper
import json
from sqlalchemy.orm import class_mapper

class ShopConfigService(ServiceBase):
    '''
    分店配置类信息操作:
    1. download configure
    2. update configure
    3. insert configure
    4. delete configure
    
    '''

    def __init__(self, start_response):
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()
        
        
    def application(self, params,paths):
        
        #检查 TOKEN 的有效性 
        dbsession =self._returndbsession()
        typestr=params.getfirst("type")
        if typestr!="all":
            company_id=params.getfirst("company_id");
            username=params.getfirst("username");
            token=params.getfirst("token");
        
            intcomp = LoginSessionManager.isValidSession(company_id, username, token, dbsession)
      
            if intcomp==False:
                return self._responseError(107, 'TOKEN 已经过期')
            
        
        #开始分流  get or set         
        if paths[2] == 'get':
            return self.getConfigApplication(params)
        elif paths[2] == 'set':
            return self.setConfigApplication(params)
             
             
        
        return self._responseError(-1, "操作失败")

      
      
    

        
    def setConfigApplication(self, params):
        '''
        set shop configuration
        '''
       
        if params.has_key('config_table') == False:
            self.debug.e('ShopConfigService.setConfigApplication:no \'config_table\' parameters')
            return self._responseInvalidParam()
        
                
        config_table = params.getfirst('config_table')
        
        
        config_table_classes = {}
        config_table_classes["config_cook_method_class"] = config_cook_method_class.ConfigCookMethodClass
        config_table_classes["config_cook_method"] = config_cook_method.ConfigCookMethod
        config_table_classes["config_cook_relation"] = config_cook_relation.ConfigCookRelation
        config_table_classes["config_dish_class"] = config_dish_class.ConfigDishClass
        config_table_classes["config_dish"] = config_dish.ConfigDish
        config_table_classes["config_floor"] = config_floor.ConfigFloor
        config_table_classes["config_order_mode"] = config_order_mode.ConfigOrderMode
        config_table_classes["config_payment"] = config_payment.ConfigPayment
        config_table_classes["config_printers"] = config_printers.ConfigPrinters
        config_table_classes["config_reason"] = config_reason.ConfigReason
        config_table_classes["config_room"] = config_room.ConfigRoom
        config_table_classes["config_stat_class"] = config_stat_class.ConfigStatClass
        config_table_classes["config_unit_relation"] = config_unit_relation.ConfigUnitRelation
        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            return self.setConfigAction(params, table_class)
        else:
            return self.response(-1, "unkonw configure")
        
    def setConfigAction(self, params, table_class):
        '''
        对写配置的响应
        table_class 要操作的表对应的ORM类
        '''
        try:

            cmd = params.getfirst('cmd')
            #过滤出要更新的表字段名和字段值
            exclude_fields = ['company_id','op_shop_id', 'username', 
                              'token', 'cmd', 'config_table', 'where_name', 
                              'where_value', 'sign']
            
            table_fields = {}
            for param in params.keys():
                if param not in exclude_fields:
                    table_fields[param] = params.getfirst(param)
                    
            company_id = params.getfirst('company_id')
            shop_id = params.getfirst('op_shop_id')
            table_class.doMapping(company_id, shop_id)            
            dbsession =self._returndbsession()       
            if cmd == 'add':
                # 增加记录操作                
                table_object = table_class()
                for field in table_fields:
                    table_object.__setattr__(field, table_fields[field])
                    
                try:
                    dbsession.add(table_object)
                    dbsession.commit()
                except Exception, e:
                    self.debug.e("ShopConfigService.setConfigAction() add table %s failed" % table_object)
                   
                    return self._responseError(-1, "%s" % e);
                
               
                output = {"ret":0,"msg":"add ok"}
                return self._response(json.dumps(output))
            elif cmd == 'update':
                
                #更新记录操作
                #获取要修改的表where字段
                where_name = params.getfirst('where_name')
                where_value = params.getfirst('where_value')
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                query_result = dbsession.query(table_class).filter(columnAttr == where_value)
                
                if query_result.count() ==0:
             
                    self.debug.e("ShopConfigService.setConfigAction(): no such record")
                    return self._responseError(-1, "该记录不存在")
                
                
                for table_object in query_result:
                    for field in table_fields:
                        table_object.__setattr__(field, table_fields[field])
                        
                dbsession.commit()
  
                output = {'ret':0, 'msg' : 'update ok'}
                return self._response(json.dumps(output))
            elif cmd == 'del':                
                #删除记录操作
                
                where_name = params.getfirst('where_name')
                where_value = params.getfirst('where_value')
                #get the column attribute
                columnAttr = getattr(table_class, where_name)
                
                dbsession.query(table_class).filter(columnAttr == where_value).delete()
                dbsession.commit()
    
                
                output = {'ret':0, 'msg' : 'delete ok'}
                return self._response(json.dumps(output))
        except Exception, e:
  
            self.debug.e('ShopConfigService.setConfigAction(): exception:%s' % e)
            return self._responseError(-1,'%s ' % e)
        
    def getConfigApplication(self, params):
        '''
        get shop configuration
        '''
        #TODO:       
        if params.has_key('type') == False:
            self.debug.e('ShopConfigService.setConfigApplication:no \'type\' parameters')
            return self._responseInvalidParam()
        
                
        config_table = params.getfirst('type')
        if config_table=="all":
            
            return self.getConfigAll(params)
        
        
        self.debug.d("tablename:%s" % config_table)
        config_table_classes = {}
        config_table_classes["config_cook_method_class"] = config_cook_method_class.ConfigCookMethodClass
        config_table_classes["config_cook_method"] = config_cook_method.ConfigCookMethod
        config_table_classes["config_cook_relation"] = config_cook_relation.ConfigCookRelation
        config_table_classes["config_dish_class"] = config_dish_class.ConfigDishClass
        config_table_classes["config_dish"] = config_dish.ConfigDish
        config_table_classes["config_floor"] = config_floor.ConfigFloor
        config_table_classes["config_order_mode"] = config_order_mode.ConfigOrderMode
        config_table_classes["config_payment"] = config_payment.ConfigPayment
        config_table_classes["config_printers"] = config_printers.ConfigPrinters
        config_table_classes["config_reason"] = config_reason.ConfigReason
        config_table_classes["config_room"] = config_room.ConfigRoom
        config_table_classes["config_stat_class"] = config_stat_class.ConfigStatClass
        config_table_classes["config_unit_relation"] = config_unit_relation.ConfigUnitRelation
        
        
        #排序字段列表
        config_orderby = {}
        config_orderby["config_cook_method_class"] ="rank_id"
        config_orderby["config_cook_method"] = "rank_id"
        config_orderby["config_cook_relation"] = "id"
        config_orderby["config_dish_class"] = "rank_id"
        config_orderby["config_dish"] = "rank_id"
        config_orderby["config_floor"] = "rank_id"
        config_orderby["config_order_mode"] = "order_mode_class asc,rank_id asc"
        config_orderby["config_payment"] = "id"
        config_orderby["config_printers"] = "id"
        config_orderby["config_reason"] = "problem_class asc ,rank_id asc"
        config_orderby["config_room"] = "rank_id"
        config_orderby["config_stat_class"] = "rank_id"
        config_orderby["config_unit_relation"] = "inner_rank_id"

        
        if config_table in config_table_classes:
            table_class = config_table_classes[config_table]
            orderby=config_orderby[config_table]
            return self.getConfigAction(params, table_class,orderby)
        else:
            return self.response(-1, "unkonw configure")
        
 
        


    def getConfigAll(self, params):
        '''
                    匹配公司ID和SHOPID
        '''
        try:
                 
            cdkey = params.getfirst('cdkey')
            uuid = params.getfirst('uuid')
        
            if cdkey == None or uuid == None :
                return self._responseInvalidParam()
        
            dbsession =self._returndbsession()
            
            dbmapb=CdkeyManager.hasbindUuidCDkey(cdkey, uuid, dbsession)
        
            if dbmapb is None:
                #response cdkey invalid, login failed
                self.debug.e('bindUuidCDkey:error %s' % cdkey)
                return self._responseError(103, "CDKEY无效")
        
        
            #response_params={}
            #response_params["ret"]=0
            #response_params["msg"]="success"
            filname="shop_config_%s_%s.sqlite" % (dbmapb[0],dbmapb[1])
          
            file_object = open('/var/www/wsgi/dbbase/%s' % filname, 'rb')
            sb = file_object.read()
            file_object.close()
            #hexstr = binascii.b2a_hex(sb) 
            #self.debug.d("line:%s" % hexstr)        
                                
            #response_params["data"]=sb            
            #strtemp=json.dumps(response_params)    
            return self._responsefiles(sb)         
        except Exception, e:
 
            self.debug.e('ShopConfigService.getConfigAction()222: exception:%s' % e)
            return self._responseInvalidParam()
        



        
        
    def getConfigAction(self, params, table_class,orderby):
        '''
                       对读配置的响应
        table_class 要操作的表对应的ORM类
        '''
        try:

            #过滤出要更新的表字段名和字段值
            dbsession =self._returndbsession()
            company_id = params.getfirst('company_id')
            shop_id = params.getfirst('op_shop_id')
            table_class.doMapping(company_id, shop_id)            
            table_fields = {}                       
            for col in (class_mapper(table_class).mapped_table.c):
                table_fields[col.name]=col.name
                                                    
            #获取记录操作                      
            if params.has_key('zfilter_where') == False:
                query_result = dbsession.query(table_class).filter().order_by(orderby).all()
            else:
                query_result = dbsession.query(table_class).filter(params.getfirst('zfilter_where')).order_by(orderby).all()
                                        
            returnlist=[]
                
            dicmy={}
            dicmy["ret"]=0
            dicmy["msg"]="success"
            icount=0
            
            for r in query_result:
                icount=1
                dicmydata={}       
                for field in  table_fields:
                    temp=getattr(r, table_fields[field])                  
                    if type(temp) is datetime.datetime:
                        dicmydata[field]=str(temp)                        
                    else:
                        dicmydata[field]=temp
                         
                strtemp=json.dumps(dicmydata)
                returnlist.append(strtemp)   

            if icount == 0:    
            
                return self._responseError(6, "记录为空")                
                    
            dicmy['data']=returnlist
 
            return self._response(json.dumps(dicmy))         
        except Exception, e:
 
            self.debug.e('ShopConfigService.getConfigAction(): exception:%s' % e)
            return self._responseInvalidParam()
        
    
    
        
